package com.lhkj.ct.base.json;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.regex.Pattern;

public class MyLocalTimeDeserializer extends JsonDeserializer<LocalTime> {

    /**
     * 校验字符串是否符合HH:mm时间格式
     */
    private static final Pattern HH_MM_PATTERN = Pattern.compile("^\\d{2}:\\d{2}$");

    /**
     * 校验字符串是否符合HH:mm时间格式
     */
    private static final Pattern HH_PATTERN = Pattern.compile("^\\d{2}$");

    /**
     * 默认Time格式
     */
    private static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

    /**
     * Time 时分格式, HH:mm
     */
    private static final String HH_MM_FORMAT = "HH:mm";

    /**
     * Time 时格式, HH
     */
    private static final String HH_FORMAT = "HH";


    @Override
    public LocalTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        String source = jsonParser.getValueAsString();
        if (StringUtils.isBlank(source)) {
            return null;
        }
        if (HH_MM_PATTERN.matcher(source).matches()){
            return LocalTime.parse(source, DateTimeFormatter.ofPattern(HH_MM_FORMAT));
        }
        if (HH_PATTERN.matcher(source).matches()){
            return LocalTime.parse(source, DateTimeFormatter.ofPattern(HH_FORMAT));
        }
        return LocalTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT));
    }

}
